package cn.lisens.demo.config;

import java.util.Properties;
import java.util.concurrent.ScheduledThreadPoolExecutor;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import com.alibaba.druid.pool.DruidDataSource;

@Configuration
@PropertySource({"classpath:database.properties"})
@EnableTransactionManagement
public class DataSourceConfig {

	@Autowired
	private Environment env;
	
	
	@Bean("Druid-CP-Create")
	public ScheduledThreadPoolExecutor druidCreate() {
		ScheduledThreadPoolExecutor poolExecuter = new ScheduledThreadPoolExecutor(3);
		return poolExecuter;
	}
	@Bean("Druid-CP-Destroy")
	public ScheduledThreadPoolExecutor druidDestroy() {
		ScheduledThreadPoolExecutor poolExecuter = new ScheduledThreadPoolExecutor(3);
		return poolExecuter;
	}
	
	@Bean(name = "dataSource",initMethod = "init",destroyMethod = "close")
	public DruidDataSource dataSource() {
		DruidDataSource dataSource = new DruidDataSource();
		dataSource.setDriverClassName(env.getRequiredProperty("jdbc.driverClassName"));
		dataSource.setUrl(env.getRequiredProperty("jdbc.url"));
		dataSource.setUsername(env.getRequiredProperty("jdbc.username"));
		dataSource.setPassword(env.getRequiredProperty("jdbc.password"));
		dataSource.setInitialSize(env.getRequiredProperty("jdbc.initialSize",Integer.class));
		dataSource.setMinIdle(env.getRequiredProperty("jdbc.minIdle",Integer.class));
		dataSource.setMaxActive(env.getRequiredProperty("jdbc.maxActive",Integer.class));
		dataSource.setMaxWait(env.getRequiredProperty("jdbc.maxWait",Integer.class));
		dataSource.setTimeBetweenEvictionRunsMillis(env.getRequiredProperty("jdbc.timeBetweenEvictionRunsMillis",Integer.class));
		dataSource.setMinEvictableIdleTimeMillis(env.getRequiredProperty("jdbc.minEvictableIdleTimeMillis",Integer.class));
		
		dataSource.setCreateScheduler(druidCreate());
		dataSource.setDestroyScheduler(druidDestroy());
	
	    dataSource.setKeepAlive(true);//空闲连接保活
	    dataSource.setValidationQuery("SELECT 1");
	    dataSource.setTestWhileIdle(true);
	    dataSource.setTestOnBorrow(true);
	    dataSource.setTestOnReturn(false);
		return dataSource;
	}
}
